<template>
  <div class="register-page">
    <!-- 顶部导航 -->
    <van-nav-bar
      title="注册"
      left-arrow
      @click-left="$router.go(-1)"
    />

    <!-- 注册表单 -->
    <div class="register-form">
      <!-- Logo -->
      <div class="logo-section">
        <div class="logo">⚖️</div>
        <h1 class="app-name">维权力</h1>
        <p class="app-desc">加入我们，开始维权之路</p>
      </div>

      <!-- 表单内容 -->
      <van-form @submit="handleRegister">
        <van-field
          v-model="form.phone"
          type="tel"
          label="手机号"
          placeholder="请输入手机号"
          :rules="phoneRules"
          maxlength="11"
        />
        
        <van-field
          v-model="form.smsCode"
          label="验证码"
          placeholder="请输入验证码"
          :rules="[{ required: true, message: '请输入验证码' }]"
          maxlength="6"
        >
          <template #button>
            <van-button
              size="small"
              type="primary"
              :disabled="smsCountdown > 0"
              @click="sendSms"
            >
              {{ smsCountdown > 0 ? `${smsCountdown}s` : '发送验证码' }}
            </van-button>
          </template>
        </van-field>

        <van-field
          v-model="form.password"
          type="password"
          label="密码"
          placeholder="请输入密码（6-20位）"
          :rules="passwordRules"
        />

        <van-field
          v-model="form.confirmPassword"
          type="password"
          label="确认密码"
          placeholder="请再次输入密码"
          :rules="confirmPasswordRules"
        />

        <van-field
          v-model="form.nickname"
          label="昵称"
          placeholder="请输入昵称（可选）"
          maxlength="20"
        />

        <!-- 地区选择 -->
        <van-field
          v-model="locationText"
          label="所在地区"
          placeholder="请选择所在地区（可选）"
          readonly
          @click="showLocationPicker = true"
        />

        <!-- 用户协议 -->
        <div class="agreement-section">
          <van-checkbox v-model="agreeTerms">
            我已阅读并同意
            <span class="link" @click="showUserAgreement">《用户协议》</span>
            和
            <span class="link" @click="showPrivacyPolicy">《隐私政策》</span>
          </van-checkbox>
        </div>

        <!-- 注册按钮 -->
        <div class="register-actions">
          <van-button
            type="primary"
            size="large"
            block
            :loading="loading"
            native-type="submit"
          >
            注册
          </van-button>
          
          <div class="action-links">
            <span @click="$router.push('/login')">已有账号？立即登录</span>
          </div>
        </div>
      </van-form>
    </div>

    <!-- 地区选择器 -->
    <van-popup v-model:show="showLocationPicker" position="bottom">
      <van-area
        :area-list="areaList"
        @confirm="onLocationConfirm"
        @cancel="showLocationPicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const smsCountdown = ref(0)
const agreeTerms = ref(false)
const showLocationPicker = ref(false)

const form = reactive({
  phone: '',
  smsCode: '',
  password: '',
  confirmPassword: '',
  nickname: '',
  province: '',
  city: '',
  district: ''
})

// 地区数据（简化版，实际项目中应该从API获取）
const areaList = ref({
  province_list: {
    110000: '北京市',
    120000: '天津市',
    310000: '上海市',
    440000: '广东省',
    110000: '北京市'
  },
  city_list: {
    110100: '北京市',
    120100: '天津市',
    310100: '上海市',
    440100: '广州市',
    440300: '深圳市'
  },
  county_list: {
    110101: '东城区',
    110102: '西城区',
    440103: '荔湾区',
    440104: '越秀区'
  }
})

// 地区显示文本
const locationText = computed(() => {
  if (form.province && form.city) {
    return form.district 
      ? `${form.province} ${form.city} ${form.district}`
      : `${form.province} ${form.city}`
  }
  return ''
})

// 表单验证规则
const phoneRules = [
  { required: true, message: '请输入手机号' },
  { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
]

const passwordRules = [
  { required: true, message: '请输入密码' },
  { min: 6, max: 20, message: '密码长度为6-20位' }
]

const confirmPasswordRules = [
  { required: true, message: '请确认密码' },
  {
    validator: (value) => {
      if (value !== form.password) {
        return '两次输入的密码不一致'
      }
      return true
    }
  }
]

// 发送短信验证码
const sendSms = async () => {
  if (!form.phone) {
    showToast('请输入手机号')
    return
  }
  
  if (!/^1[3-9]\d{9}$/.test(form.phone)) {
    showToast('手机号格式不正确')
    return
  }

  try {
    await userStore.sendSmsCode(form.phone)
    showToast('验证码发送成功')
    
    // 开始倒计时
    smsCountdown.value = 60
    const timer = setInterval(() => {
      smsCountdown.value--
      if (smsCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error) {
    showToast(error.message || '验证码发送失败')
  }
}

// 地区选择确认
const onLocationConfirm = ({ selectedValues, selectedOptions }) => {
  form.province = selectedOptions[0]?.text || ''
  form.city = selectedOptions[1]?.text || ''
  form.district = selectedOptions[2]?.text || ''
  showLocationPicker.value = false
}

// 注册处理
const handleRegister = async () => {
  if (!agreeTerms.value) {
    showToast('请先同意用户协议和隐私政策')
    return
  }

  loading.value = true
  
  try {
    await userStore.register(form)
    showToast('注册成功')
    router.push('/login')
  } catch (error) {
    showToast(error.message || '注册失败')
  } finally {
    loading.value = false
  }
}

// 显示用户协议
const showUserAgreement = () => {
  showToast('用户协议页面开发中')
}

// 显示隐私政策
const showPrivacyPolicy = () => {
  showToast('隐私政策页面开发中')
}
</script>

<style scoped>
.register-page {
  min-height: 100vh;
  background: #f7f8fa;
}

.register-form {
  padding: 0 24px;
}

.logo-section {
  text-align: center;
  padding: 40px 0 32px;
}

.logo {
  font-size: 64px;
  margin-bottom: 16px;
}

.app-name {
  font-size: 28px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 8px;
}

.app-desc {
  font-size: 14px;
  color: #969799;
}

.agreement-section {
  padding: 16px 16px 0;
}

.agreement-section .link {
  color: #1989fa;
  cursor: pointer;
}

.register-actions {
  margin-top: 32px;
}

.action-links {
  text-align: center;
  margin-top: 16px;
  font-size: 14px;
  color: #1989fa;
}

.action-links span {
  cursor: pointer;
}
</style>